<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <link rel="stylesheet" href="//unpkg.com/layui@2.6.8/dist/css/layui.css" />
    <!-- 引入 layui.js -->
    <script src="jquery-3.6.1.min.js"></script>
    <script src="//unpkg.com/layui@2.6.8/dist/layui.js"></script>
    <link rel="stylesheet" href="../bootstrap-3.4.1/dist/css/bootstrap.css" />
    <script src="../bootstrap-3.4.1/dist/js/bootstrap.js"></script>
    <script src="city.js"></script>
    <style>
      body {
        background-color: #f5f5f5;
      }
      #box {
        width: 1260px;
        margin: 50px auto 0;
      }
      .layui-table-cell {
        height: 60px;
        line-height: 60px;
      }
      #xiang {
        display: none;
        text-align: center;
        position: fixed;
        top: 30px;
        left: 30%;
        width: 700px;
        height: 600px;
        padding-left: 30px;
        padding: 30px;
        background-color: #fff;
        z-index: 9999;
      }
      #xiang input {
        font-family: Microsoft YaHei, Heiti SC, tahoma, arial, Hiragino Sans GB,
          "\5B8B\4F53", sans-serif;
        width: 600px;
        height: 35px;
        margin-top: 20px;
      }
      #sex {
        width: 600px;
        height: 35px;
        margin-top: 20px;
      }
      #btncss {
        width: 100px;
        height: 35px;
        color: white;
        margin-top: 20px;
        border: none;
        background-image: linear-gradient(0deg, #a8caba 0%, #5d4157 100%);
      }
      #cuo {
        position: absolute;
        top: -12px;
        right: 0px;
        cursor: pointer;
        color: black;
        font-size: 40px;
      }
      .chaoceng {
        display: none;
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background-color: rgba(0, 0, 0, 0.6);
        z-index: 999;
      }

      .sou {
        position: relative;
        top: 0;
        left: 0;
        width: 1260px;
        margin: 50px auto 0;
      }
      .sou input {
        font-family: Microsoft YaHei, Heiti SC, tahoma, arial, Hiragino Sans GB,
          "\5B8B\4F53", sans-serif;
        width: 240px;
        height: 33px;
        margin-right: 5px;
        padding: 0 10px;
        width: 268px;
        color: #999;
        border: 1px solid #d0d0d0;
      }
      .sou button {
        cursor: pointer;
        width: 76px;
        height: 35px;
        line-height: 33px;
        padding: 0;
        vertical-align: baseline !important;
        text-align: center;
        vertical-align: middle;
        white-space: nowrap;
        font-weight: normal;
        font-size: 14px;
        background: none repeat scroll 0 0 #f04243;
        border: 0 none;
        color: #ffffff;
      }
      .search-img {
        display: none;
        position: absolute;
        top: 1px;
        left: 10%;
        height: 0;
        width: 24px;
        z-index: -1;
      }
      b {
        font-family: Microsoft YaHei, Heiti SC, tahoma, arial, Hiragino Sans GB,
          "\5B8B\4F53", sans-serif;
        margin-right: 5px;
      }
    </style>
  </head>
  <body>
    <div class="sou">
      <div class="search-img"><img src="../image/chicken.gif" alt="" /></div>
      <input type="text" id="ipt" / placeholder="请输入名字搜索">
      <button id="btnsuo">搜索</button>
    </div>
    <div class="chaoceng"></div>
    <div id="xiang">
      <b>&emsp;ID:</b><input type="text" id="ids" disabled /><br />
      <b>用户:</b><input type="text" id="username" disabled /><br />
      <b>性别:</b
      ><select name="sex" id="sex">
        <option value="1">男</option>
        <option value="2">女</option>
      </select>
      <br />
      <b>年龄:</b><input type="text" id="age" placeholder="输入数字" /><br />
      <b>省市:</b><input type="text" id="province" /><br />
      <b>市区:</b><input type="text" id="city" /><br />
      <b>县乡:</b><input type="text" id="area" /><br />
      <b>详址:</b><input type="text" id="detail_address" /><br />
      <b>图片:</b><input type="text" id="img" /><br />
      <button id="btncss">保存修改</button>
      <div id="cuo">×</div>
    </div>
    <div class="table-responsive" id="box">
      <table id="userList" lay-filter="userList"></table>
    </div>
  </body>
  <script type="text/html" id="tab-img">
    <img
      src="{{ d.img }}"
      style="width: 50px;height: 50px; border-radius: 25px;"
    />
  </script>
  <script type="text/html" id="barDemo">
    <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
  </script>
  <script>
    //获取焦点
    $("#ipt").focus(function () {
      $(".search-img").animate(
        {
          top: "-22px",
        },
        500
      );
      $(".search-img").show();
    });
    //失去焦点
    $("#ipt").blur(function () {
      $(".search-img").animate(
        {
          top: "1px",
        },
        500
      );
    });

    $("#cuo").click(function () {
      $("#xiang").hide();
      $(".chaoceng").hide();
    });

    layui.use("table", function () {
      $("#btncss").click(btncssFun);
      var table = layui.table;

      //第一个实例
      table.render({
        elem: "#userList",
        height: 650,
        headers: {
          Authorization: "Bearer " + localStorage.getItem("token"),
        },
        url: "https://api.zzgoodqc.cn/api/user", //数据接口
        page: true, //开启分页
        limit: 10,
        limits: [10, 20, 30],
        cols: [
          [
            //表头
            {
              field: "id",
              title: "ID",
              align: "center",
              width: 80,
              sort: true,
              fixed: "left",
            },
            {
              field: "img",
              title: "头像",
              templet: "#tab-img",
              align: "center",
              width: 100,
            },
            { field: "username", title: "用户名", align: "center", width: 120 },
            {
              field: "sex",
              title: "性别",
              align: "center",
              templet: function (d) {
                if (d.sex == 1) {
                  return "男";
                } else {
                  return "女";
                }
              },
              width: 120,
              sort: true,
            },
            {
              field: "age",
              title: "年龄",
              align: "center",
              width: 120,
              sort: true,
            },
            {
              field: "detail_address",
              title: "地址",
              templet: function (d) {
                  console.log(d);
                       var res = /^\d$/
                       var sheng = []
                       var shi = []
                       var shi2 = []
                       var xian = []
                       if (res.test(d.province) && res.test(d.city) && res.test(d.area)) {
                         citys.forEach((item) => {

                            sheng.push(item.name)
                         })
                         citys[d.province].city.forEach((item) => {
                            shi.push(item.name)
                         })
                         citys[d.province].city.forEach((item) => {
                            shi2.push(item.area)
                         })
                         shi2.forEach((item) => {
                            for (let i = 0; i < item.length; i++) {
                              xian.push(item[i])
                            }
                         })
                         return sheng[d.province] + shi[d.city] + xian[d.area]
                       }
                       return d.province + d.city + d.area
                    },
              align: "center",
              width: 180,
            },
            {
              field: "created_at",
              title: "创建时间",
              align: "center",
              width: 180,
              sort: true,
            },
            {
              field: "updated_at",
              title: "更新时间",
              align: "center",
              width: 180,
              sort: true,
            },
            {
              fixed: "right",
              title: "操作",
              width: 170,
              align: "center",
              toolbar: "#barDemo",
            },
          ],
        ],
        parseData: function (res) {
          return {
            code: 0,
            msg: res.msg,
            count: res.count,
            data: res.data,
          };
        },
      });
      table.on("tool(userList)", function (obj) {
        //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
        var data = obj.data; //获得当前行数据
        var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
        var tr = obj.tr; //获得当前行 tr 的 DOM 对象（如果有的话）

        if (layEvent === "detail") {
          //查看
          //do somehing
        } else if (layEvent === "del") {
          //删除
          layer.confirm("真的删除行么", function (index) {
            obj.del(); //删除对应行（tr）的DOM结构，并更新缓存
            layer.close(index);
            var ids = data.id;
            $.ajax({
              url: "https://api.zzgoodqc.cn/api/user/" + ids,
              type: "DELETE",
              headers: {
                Authorization: "Bearer " + localStorage.getItem("token"),
              },
              success: function (res) {
                if (res.code == 200) {
                  layer.msg(res.message);
                }
              },
              dataType: "json  ",
            });
            //向服务端发送删除指令
          });
        } else if (layEvent === "edit") {
          //编辑
          //do something
          $("#xiang").show();
          $(".chaoceng").show();
          $("#ids").val(data.id);
          $("#username").val(data.username);
          $("#sex").val(data.sex ?? "");
          $("#age").val(data.age ?? "");
          $("#province").val(data.province ?? "");
          $("#city").val(data.city ?? "");
          $("#area").val(data.area ?? "");
          $("#detail_address").val(data.detail_address ?? "");
          $("#img").val(data.img ?? "");
          //同步更新缓存对应的值
          obj.update({
            username: "123",
            title: "xxx",
          });
        } else if (layEvent === "LAYTABLE_TIPS") {
          layer.alert("Hi,头部工具栏扩展的右侧图标。");
        }
      });

      $("#btnsuo").click(btnsuoFun);
      $("#ipt").keyup(btnsuoFun);
      //点击搜索
      function btnsuoFun() {
        if (event.key == "Enter" || event.type == "click") {
          table.render({
            elem: "#userList",
            height: 650,
            headers: {
              Authorization: "Bearer " + localStorage.getItem("token"),
            },
            url:
              "https://api.zzgoodqc.cn/api/searchUser?key=" + $("#ipt").val(), //数据接口
            page: true, //开启分页
            limit: 10,
            limits: [10, 20, 30],
            cols: [
              [
                //表头
                {
                  field: "id",
                  title: "ID",
                  align: "center",
                  width: 80,
                  sort: true,
                  fixed: "left",
                },
                {
                  field: "img",
                  title: "头像",
                  templet: "#tab-img",
                  align: "center",
                  width: 100,
                },
                {
                  field: "username",
                  title: "用户名",
                  align: "center",
                  width: 120,
                },
                {
                  field: "sex",
                  title: "性别",
                  align: "center",
                  templet: function (d) {
                    if (d.sex == 1) {
                      return "男";
                    } else if (d.sex == 2) {
                      return "女";
                    } else if (d.sex == null) {
                      return "未定义";
                    }
                  },
                  width: 120,
                  sort: true,
                },
                {
                  field: "age",
                  title: "年龄",
                  align: "center",
                  width: 120,
                  sort: true,
                },
                {
                  field: "detail_address",
                  title: "地址",
                  align: "center",
                  width: 180,
                },
                {
                  field: "created_at",
                  title: "创建时间",
                  align: "center",
                  width: 180,
                  sort: true,
                },
                {
                  field: "updated_at",
                  title: "更新时间",
                  align: "center",
                  width: 180,
                  sort: true,
                },
                {
                  fixed: "right",
                  title: "操作",
                  width: 170,
                  align: "center",
                  toolbar: "#barDemo",
                },
              ],
            ],
            parseData: function (res) {
              return {
                code: 0,
                msg: res.msg,
                count: res.count,
                data: res.data,
              };
            },
          });
        }
      }
      //点击添加
      function btncssFun() {
        var xid = $("#ids").val();
        let date = {
          sex: $("#sex").val(),
          age: $("#age").val(),
          province: $("#province").val(),
          city: $("#city").val(),
          area: $("#area").val(),
          detail_address: $("#detail_address").val(),
          img: $("#img").val(),
        };
        $.ajax({
          url: "https://api.zzgoodqc.cn/api/user/" + xid,
          type: "PUT",
          data: date,
          headers: {
            Authorization: "Bearer " + localStorage.getItem("token"),
          },
          dataType: "json",
          success: function (res) {
            if (res.code == 200) {
              $("#xiang").hide();
              $(".chaoceng").hide();
              layer.alert(res.message);
              table.reload("userList", {});
            } else {
              alert(res.message);
            }
          },
        });
      }
    });

    // layui.use('laypage', function(){
    //   var laypage = layui.laypage;

    //   //执行一个laypage实例
    //   laypage.render({
    //     elem: 'test1' //注意，这里的 test1 是 ID，不用加 # 号
    //     ,count: 50 //数据总数，从服务端得到
    //   });
    // });
  </script>
</html>
